/**
 * AsyncDemo :	A simple demo showing Asynchronous funcitonality
 * 
 * @langversion		HaXe 2
 * @targets			cpp, flash, flash9, js, neko, php
 * @author			Justin Donaldson | jdonaldson@gmail.com
 * @since			2010-08-20
 */

using Async;
class AsyncDemo
{

	public function new()
	{
		
	}

	public static function main(): Void
	{
		// an asynchronous variable.  asynchronous functionality is built around these types, along with special
		// "using" syntax for function types.
		var av = new Async<Int>();
		
		
		// wait on a simple integer...
		var v1 = foo.wait1(av);
		
		// wait on a complex function that mixes asynchronous values and normal values.
		var v2 = bar.wait2(v1, 'words!');
		
		// wait on an even more complex function that mixes two different asynchronous values...
		var av2 = new Async<String>();
		baz.wait2(v2, av2);  // the result from v2, which relies on v1, which relies on av.
		
		// yield for the first asynchronous variable. foo() will fire now.  after it is done, bar will fire.
		// baz() will check to see if it can fire, but it is missing av2.
		av.yield(4);
		
		//yield for the second. baz() can fire now.
		av2.yield('hi');
		
		
		// reset the value, clear the listeners for av
		av.reset();		

		
		// start a new wait on the reset value av
		bing.wait1(av);
		
		// do a classic loop and yield the values through av.
		for ( i in 0...10){
			av.yield(i);
		}
		
	}
	
	public static function foo(a:Async<Int>) : Async<Int>{
		var b = new Async<Int>();
		trace("foo saw a: " + a);
		
		b.yield(a.val + 1);
		return b;
	}
	
	public static function bar(a:Async<Int>, baz:String) :  Async<String>{
		var b = new Async<String>();
		trace('bar is converting an Async int to a string, modifying, and returning it');
		b.yield( Std.string('results from bar: ' + a.val + ' ' + baz));
		return b;
	}
	
	public static function baz(b:Async<String>, c:Async<String>){
		trace("baz saw b: " + Std.string(b)); 
		trace("baz saw c: " + Std.string(c)); 
	}

	public static function bing(b:Async<Int>){
		trace(Math.pow(b.val,2));
	}



}

